package com.mySampleApplication.server;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mySampleApplication.client.CodeRuleAtter.CodeRuleAtterDto;
import com.mySampleApplication.client.CodeRuleAtter.CodeRuleAtterService;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 编码规则分段
 */
public class CodeRuleAtterServlet extends RemoteServiceServlet implements CodeRuleAtterService {

    /**
     * 查询总数
     * @param map 条件
     */
    public String getTotal(Map<String, String> map) {
        String total="0";
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {
            if(map.size()>0 && !map.isEmpty()){
                map.forEach((k,v)->{
                    if(map.size()==1){
                        str.append(k).append(" like").append("'%"+v+"%'");
                    }else if (map.size()>1){
                        str.append(" and ").append(k).append(" like ").append("'%"+v+"%'");
                    }

                });
            }
            conn = ds.getConnection();
            String sql="select * from code_rule";
            if(!str.toString().equals("")){
                sql=sql+" where " +str.toString();
            }
            List<Entity> totalList = SqlExecutor.query(conn, sql, new EntityListHandler());
            total=totalList.get(0).get("total").toString();
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return total;
    }

    /**
     * 查询list
     * @param map 条件
     * @param mapPage 分页
     */
    public CodeRuleAtterDto getSelect(Map<String, String> map, Map<String, String> mapPage) {
        Map<String, Object> reMap = new HashMap<>();
        CodeRuleAtterDto dto =new CodeRuleAtterDto();
        int pageSize =(Integer.parseInt (mapPage.get("pageSize"))-1)*Integer.parseInt (mapPage.get("pageNumber"));
        int pageNumber = Integer.parseInt (mapPage.get("pageNumber"));
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {
            if(map.size()>0 && !map.isEmpty()){
                map.forEach((k,v)->{
                    if(map.size()==1){
                        str.append(k).append(" = ").append("'"+v+"'");
                    }else if (map.size()>1){
                        str.append(" and ").append(k).append(" like").append("'%"+v+"%'");
                    }

                });
            }
            String sql="select * from code_rule_atter";
            if(!str.toString().equals("")){
                sql=sql+"  where " +str.toString();
            }
            conn = ds.getConnection();
            List<Entity> totalList = SqlExecutor.query(conn, sql, new EntityListHandler());
            List<Entity> entityList = SqlExecutor.query(conn, sql+" ORDER BY fdsx " , new EntityListHandler());
//            for (Entity entity : entityList) {
//                System.out.println(entity.get("user_name"));
//            }
//            reMap.put("totalData",totalList.get(0));
//            reMap.put("entityList",entityList);
            reMap.put("entityList", BeanUtil.copyToList(entityList, Map.class));
            List<Map<String,String>> list =new ArrayList<>();
            Map<String, String> mapp;
            for (Map  a:BeanUtil.copyToList(entityList, Map.class)) {
                mapp= new HashMap<>();
                Map<String, String> finalMapp = mapp;
                a.forEach((k, v)->{
                    finalMapp.put(String.valueOf(k),v==null?"":v+"") ;
                });
                list.add(finalMapp);
            }
            dto.setKeyValueMap(list);
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return dto;
    }

    /**
     * 查询list
     * @param map 条件
     * @param mapPage 分页
     */
    public CodeRuleAtterDto getSelectVs(Map<String, String> map, Map<String, String> mapPage) {
        Map<String, Object> reMap = new HashMap<>();
        CodeRuleAtterDto dto =new CodeRuleAtterDto();
        int pageSize =(Integer.parseInt (mapPage.get("pageSize"))-1)*Integer.parseInt (mapPage.get("pageNumber"));
        int pageNumber = Integer.parseInt (mapPage.get("pageNumber"));
        StringBuffer str = new StringBuffer();
        str.append("1=1");
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {
            if(map.size()>0 && !map.isEmpty()){
                map.forEach((k,v)->{
                    if(map.size()==1){
                        str.append(k).append(" = ").append("'"+v+"'");
                    }else if (map.size()>1){
                        str.append(" and ").append(k).append(" = ").append("'"+v+"'");
                    }

                });
            }
            String sql="select * from code_rule_atter_version";
            if(!str.toString().equals("")){
                sql=sql+"  where " +str.toString();
            }
            conn = ds.getConnection();
            List<Entity> totalList = SqlExecutor.query(conn, sql, new EntityListHandler());
            List<Entity> entityList = SqlExecutor.query(conn, sql+" ORDER BY fdsx " , new EntityListHandler());
//            for (Entity entity : entityList) {
//                System.out.println(entity.get("user_name"));
//            }
//            reMap.put("totalData",totalList.get(0));
//            reMap.put("entityList",entityList);
            reMap.put("entityList", BeanUtil.copyToList(entityList, Map.class));
            List<Map<String,String>> list =new ArrayList<>();
            Map<String, String> mapp;
            for (Map  a:BeanUtil.copyToList(entityList, Map.class)) {
                mapp= new HashMap<>();
                Map<String, String> finalMapp = mapp;
                a.forEach((k, v)->{
                    finalMapp.put(String.valueOf(k),v==null?"":v+"") ;
                });
                list.add(finalMapp);
            }
            dto.setKeyValueMap(list);
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return dto;
    }


    /**
     * 根据编码规则id查询
     */
    public static CodeRuleAtterDto getSelectById(String cId) {
        Map<String, Object> reMap = new HashMap<>();
        CodeRuleAtterDto dto =new CodeRuleAtterDto();
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {

            String sql="select * from code_rule_atter where coderule_id='"+cId +"' ORDER BY fdsx ";
            conn = ds.getConnection();
            List<Entity> entityList = SqlExecutor.query(conn, sql, new EntityListHandler());
            reMap.put("entityList", BeanUtil.copyToList(entityList, Map.class));
            List<Map<String,String>> list =new ArrayList<>();
            Map<String, String> mapp;
            for (Map  a:BeanUtil.copyToList(entityList, Map.class)) {
                mapp= new HashMap<>();
                Map<String, String> finalMapp = mapp;
                a.forEach((k, v)->{
                    finalMapp.put(String.valueOf(k),v==null?"":v+"") ;
                });
                list.add(finalMapp);
            }
            dto.setKeyValueMap(list);
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return dto;
    }


    /**
     * 插入数据
     * @param map 数据对象
     * @return
     */
    public String setInsert(Map<String, String> map) {
        map.entrySet().removeIf(entry -> StrUtil.isBlank(entry.getValue()));
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            StringBuffer str = new StringBuffer();
            StringBuffer value = new StringBuffer();
            String timeStr1= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            str.append("(").append("create_time,");
            value.append("(").append("'"+timeStr1+"',");
            map.forEach((k, v) -> {
                str.append(k).append(",");
                value.append(v==null?v:"'"+v+"'").append(",");
            });
            str.replace(str.length() - 1, str.length(), ")");
            value.replace(value.length() - 1, value.length(), ")");
            // 插入语句
            SqlExecutor.execute(conn, "insert into code_rule_atter " + str.toString() + " value " + value.toString() + "");
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    public static String setSbInsert(Map<String, String> map) {
        map.entrySet().removeIf(entry -> StrUtil.isBlank(entry.getValue()));
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            StringBuffer str = new StringBuffer();
            StringBuffer value = new StringBuffer();
            str.append("(");
            value.append("(");
            map.forEach((k, v) -> {
                str.append(k).append(",");
                value.append(v==null?v:"'"+v+"'").append(",");
            });
            str.replace(str.length() - 1, str.length(), ")");
            value.replace(value.length() - 1, value.length(), ")");
            // 插入语句
            SqlExecutor.execute(conn, "insert into code_rule_atter_version " + str.toString() + " value " + value.toString() + "");
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    public static String setSbUpdate(Map<String, String> map) {
        map.entrySet().removeIf(entry -> StrUtil.isBlank(entry.getValue()));
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            StringBuffer str = new StringBuffer();
            StringBuffer where = new StringBuffer();
            str.append("update code_rule_atter set ");
            map.forEach((k, v) -> {
                if (!k.equals("coderule_id")) {
                    str.append(k).append("=").append(v).append(",");
                } else {
                    where.append(k).append("=").append(v);
                }
            });
            str.replace(str.length() - 1, str.length(), " ");
            String sql = str.toString() +" where "+ where.toString();
            // 更新语句
            SqlExecutor.execute(conn, sql);
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    /**
     * 修改数据
     * @param map 数据对象
     * @return
     */
    public String setUpdate(Map<String, String> map) {
        map.entrySet().removeIf(entry -> StrUtil.isBlank(entry.getValue()));
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            StringBuffer str = new StringBuffer();
            StringBuffer where = new StringBuffer();
            str.append("update code_rule_atter set ");
            map.forEach((k, v) -> {
                if (!k.equals("id")) {
                    str.append(k).append("=").append(v).append(",");
                } else {
                    where.append(k).append("=").append(v);
                }
            });
            str.replace(str.length() - 1, str.length(), " ");
            String sql = str.toString() + where.toString();
            // 更新语句
            SqlExecutor.execute(conn, sql);
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    /**
     * 批量删除数据
     * @param ids
     * @return
     */
    public String setDelete(int[] ids) {
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            Connection finalConn = conn;
            Arrays.stream(ids).forEach(a -> {
                // 删除语句
                try {
                    SqlExecutor.execute(finalConn, "delete from code_rule_atter  where id=" + a);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            });
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    /**
     * 根据编码规则id删除数据
     * @param coderuleId
     * @return
     */
    public String deleteByCoderuleId(String coderuleId) {
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            Connection finalConn = conn;
//            Arrays.stream(ids).forEach(a -> {
                // 删除语句
                try {
                    SqlExecutor.execute(finalConn, "delete from code_rule_atter  where coderule_id='" + coderuleId+"'");
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
//            });
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }
}
